package com.pine.manager.pineframework;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.excel.ExcelService;
import com.pine.dao.pineframework.entity.SysConfig;
import com.pine.dao.pineframework.mapper.SysConfigMapper;
import com.pine.manager.core.BaseManager;
import com.pine.manager.core.CacheNameConstant;
import com.pine.manager.pineframework.bo.SysConfigBo;
import com.pine.manager.pineframework.convertors.SysConfigConvertor;
import com.pine.manager.pineframework.dto.SysConfigExportDto;
import com.pine.manager.pineframework.query.SysConfigQuery;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>
 * 系统配置表 管理类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Component
public class SysConfigManager extends BaseManager<SysConfigMapper, SysConfig, Long, SysConfigBo, SysConfigQuery, SysConfigConvertor> implements ExcelService<SysConfigQuery> {

    @Resource
    private SysConfigConvertor sysConfigConvertor;

    @Override
    @Cacheable(cacheNames = CacheNameConstant.SYS_CONFIG_CACHE_NAME, key = "#query.configKey")
    public SysConfigBo getOne(SysConfigQuery query) {
        return super.getOne(query);
    }

    @Override
    public LambdaQueryWrapper<SysConfig> encapsulateQueryWrapper(SysConfigQuery query) {
        LambdaQueryWrapper<SysConfig> queryWrapper = super.encapsulateQueryWrapper(query);
        if (query == null) {
            return queryWrapper;
        }

        // 组装查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(query.getConfigName()), SysConfig::getConfigName, query.getConfigName());
        queryWrapper.eq(ObjectUtils.isNotEmpty(query.getConfigKey()), SysConfig::getConfigKey, query.getConfigKey());
        queryWrapper.eq(ObjectUtils.isNotEmpty(query.getConfigValue()), SysConfig::getConfigValue, query.getConfigValue());
        queryWrapper.eq(ObjectUtils.isNotEmpty(query.getStatus()), SysConfig::getStatus, query.getStatus());
        queryWrapper.like(ObjectUtils.isNotEmpty(query.getRemark()), SysConfig::getRemark, query.getRemark());
        queryWrapper.eq(ObjectUtils.isNotEmpty(query.getCreateUserId()), SysConfig::getCreateUserId, query.getCreateUserId());
        queryWrapper.ge(ObjectUtils.isNotEmpty(query.getUpdateTimeStart()), SysConfig::getUpdateTime, query.getUpdateTimeStart());
        queryWrapper.le(ObjectUtils.isNotEmpty(query.getUpdateTimeEnd()), SysConfig::getUpdateTime, query.getUpdateTimeEnd());

        return queryWrapper;
    }

    @Override
    public void syncExport(HttpServletResponse response, SysConfigQuery sysConfigQuery) {
        PageRequest<SysConfigQuery> pageRequest = new PageRequest<>(sysConfigQuery);
        pageRequest.exportPage();

        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), SysConfigExportDto.class).autoCloseStream(false).build()) {
            // 设置response请求头信息,文件名等信息
            setResponseAndHeaderInfo(response, "系统配置_");
            // 创建sheet页
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();

            // 执行查询分页数据信息
            long totalPage = 0L;
            while (true) {
                // 分页查询
                IPage<SysConfigBo> sysConfigBoPage = this.page(pageRequest);
                if (sysConfigBoPage.getTotal() > MAX_EXPORT_SIZE) {
                    throw new BusinessException(ExceptionCodeEnum.EXPORT_TOO_MUCH);
                }

                // 设置总页数
                if (sysConfigBoPage.getPages() != 0L) {
                    totalPage = sysConfigBoPage.getPages();
                }

                // 查到的结果为空
                if (sysConfigBoPage.getRecords().isEmpty()) {
                    break;
                }

                List<SysConfigExportDto> exportDtos = sysConfigBoPage.getRecords().stream().map(sysConfigConvertor::entityBoToExportDto).toList();
                excelWriter.write(exportDtos, writeSheet);
                // 没有下一页，跳出循环
                if (sysConfigBoPage.getCurrent() >= totalPage) {
                    break;
                }

                // 请求下一页
                pageRequest.setPageNum(pageRequest.getPageNum() + 1);
            }
        } catch (Exception e) {
            throw new BusinessException(ExceptionCodeEnum.EXPORT_ERROR);
        }
    }
}
